package com.cloudpivot.receivales.esign.controller;


import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.esign.domain.MessageEntity;
import com.cloudpivot.receivales.esign.service.ESignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * E签宝
 */
@RestController
@RequestMapping("/eSign")
@Slf4j
public class ESignController {
    @Autowired
    private ESignService eSignService;

    /**
     * 推送文件并发起E签宝审批
     */
    @PostMapping ("/pushContractAndCreateFlow")
    public MessageEntity pushContractAndCreateFlow(@RequestPart("file") MultipartFile file, @RequestParam("data") String data) throws Exception {

        JSONObject bodyJSON = JSONObject.parseObject(data);
        log.info("pushContractAndCreateFlow接收到的data："+data);
        MessageEntity resultMessage = eSignService.startFlow(file, bodyJSON);

        return resultMessage;
    }

    /**
     * 获取E签宝的Token，用于中台获取签署完成后下载文件
     */
    @GetMapping("/getESignToken")
    public MessageEntity getESignToken(){

        MessageEntity resultMessage = eSignService.getToken();

        return resultMessage;
    }

    /**
     * 下载签署完成后的文件
     */
    @GetMapping("/fileDownload")
    public MessageEntity fileDownload(@RequestParam("signFlowId") String signFlowId){

        MessageEntity resultMessage = eSignService.fileDownload(signFlowId);

        return resultMessage;
    }


    /**
     * E签宝回调接口-签署流程结束后，无论是否签署成功
     */
    @PostMapping("/callBackFromESign")
    public ResponseEntity<JSONObject> callBackFromESign(@RequestBody JSONObject entity) {
        log.info("E签宝回调接口=======>>>>>{}", entity.toJSONString());
        JSONObject resJson = new JSONObject();
        resJson.put("code", "200");
        resJson.put("msg", "success");
        if (StringUtils.isBlank(entity.getString("action"))) {
            return new ResponseEntity<JSONObject>(resJson, HttpStatus.BAD_REQUEST);
        }
        String signStatus = entity.getString("action");
        if (signStatus.equals("SIGN_FLOW_COMPLETE")) {
            checkAndPushReport(entity, entity.getString("signFlowTitle"));
        }
        return new ResponseEntity<JSONObject>(resJson, HttpStatus.OK);
    }

    @Async
    public void checkAndPushReport(JSONObject callBackBody , String flowName) {
        String signFlowId = callBackBody.getString("signFlowId");
        switch (callBackBody.getString("signFlowStatus")) {
            case "2"://已完成（所有签署方完成签署）
                log.info("签署流程已完成，signFlowId：" + signFlowId);
                if(flowName.equals("服务报告单")){
                    eSignService.pushReportToCRM(signFlowId);
                }
                if(flowName.equals("设备安装验收单")){
                    eSignService.pushReportToBPM(signFlowId);
                }
                break;
            case "3"://已撤销（发起方撤销签署任务）
                log.info("签署流程已撤销，signFlowId：" + signFlowId);
                break;
            case "5"://已过期（签署截止日到期后触发），默认签署流程创建后的90天时截止
                log.info("签署流程已过期，signFlowId：" + signFlowId);
                break;
            case "7"://已拒签（签署方拒绝签署）
                log.info("签署流程已拒签，signFlowId：" + signFlowId);
                break;
            default:
                break;
        }
    }

}
